from ihome.utils.commons import login_required
from ihome.utils.response_code import RET
from . import order_blue
from flask import g, jsonify, request, current_app, session
from ihome.models import Order, House
from ihome import db
from datetime import datetime


@order_blue.route('/', methods=['GET', 'POST', 'PUT'],strict_slashes=False)
@login_required
def orders():
    # 张鋆
    """
        添加订单
    步骤:
        1.验证用户是否登录  login_required
        2.如果未登录, 提示错误信息
        3.判断 method = 'POST'
        4.获取参数 reqst.json.get() start_date, end_date, house_id
        5.判断参数完整性
        6.house_id转换为整型
        7.根据house_id获取price
        8.start_date,end_date转成DateTime格式
        9.获取days
         from datetime import datetime
         import time
         start = '2018-11-02'
         end = '2018-11-5'
         tstart = datetime.strptime(start,'%Y-%m-%d')
         tend = datetime.strptime(end,'%Y-%m-%d')
         f = tend-tstart       # type(f) datetime.timedelta
         days = f.days

        10.获取订单总金额amount = days*price
        11.实例化Order模型类对象
        12.添加start_date,end_date,house_id,user_id,days等数据到表中,status='WAIT_ACCEPT'
        13.尝试获取刚添加的订单的id
        14.返回订单的id  return jsonify(errno='RET.OK', errmsg='OK', data=)

    :return:
    """

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登录')

    if request.method == 'POST':
        start_date = request.json.get('start_date')
        end_date = request.json.get('end_date')
        house_id = request.json.get('house_id')

        if not all([house_id, start_date, end_date]):
            return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')

        try:
            house_id = int(house_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR,errmsg='参数类型错误')

        try:
            house = House.query.filter_by(id=house_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='数据库查询错误')

        # 添加判断, 如果房子是自己的,不可以添加订单
        if house.user_id == user.id:
            return jsonify(errno=RET.DATAEXIST,errmsg='自己的房子别刷单了吧？')

        dstart_date = datetime.strptime(start_date,'%Y-%m-%d')
        dend_date = datetime.strptime(end_date,'%Y-%m-%d')
        f = dend_date - dstart_date
        days = f.days
        amount = days * house.price

        order = Order()
        order.user_id = user.id
        order.house_id = house_id
        order.begin_date = dstart_date
        order.end_date = dend_date
        order.house_price = house.price
        order.days = days
        order.amount = amount
        order.comment = ""

        try:
            db.session.add(order)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR,errmsg='数据库添加数据失败')

        try:
            order = Order.query.filter().order_by(Order.id.desc()).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='数据库查询失败')

        data = {
            "order_id": order.to_dict()
        }
        return jsonify(errno=RET.OK,errmsg='OK',data=data)



    """
        获取订单列表
    步骤:
        1.判断method = 'GET'
        2.获取参数 (request.args.get('role')), order_id
        3.判断参数完整性
        4.判断role在landlord,custom
        5.实例化order模型类对象
        6.定义空列表
        7.将order对象添加到列表中
        8.返回数据 data
        
    """

    if request.method == 'GET':
        role = request.args.get('role')
        if role not in ['landlord','custom']:
            return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

        if role=='custom':
            try:
                custom_orders = Order.query.filter(Order.user_id==user.id).all()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR,errmsg='数据库查询失败')

            custom_order_list = []
            for custom_order in custom_orders:
                custom_order_list.append(custom_order.to_dict())

            data = {
                'orders':custom_order_list
            }
            return jsonify(errno=RET.OK,errmsg='OK',data=data)

        try:
            houses = House.query.filter(House.user_id == user.id).all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='数据库查询失败')

        if not houses:
            return jsonify(errno=RET.DATAERR,errmsg='未发布房源')

        order_list = []
        for house in houses:
            try:
                orders = Order.query.filter(Order.house_id==house.id).all()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR,errmsg='数据库查询订单失败')
            for each_order in orders:
                order_list.append(each_order.to_dict())
        order_list.reverse()

        data = {
            'orders':order_list
        }


        return jsonify(errno=RET.OK,errmsg='OK',data=data)



    """
        接单和拒单
    步骤：
        1.判断method = 'PUT'
        2.获取参数 action, order_id, reason
        3.判断参数action,order_id完整性
        4.判断action在accept,reject
        5.根据order_id查找order对象
        6.如果action='reject'
        7.添加reason到数据库中,status改成'REJECTED'
        8.如果action='accept'
        9.更改status为'WAIT_PAYMENT'
        10.return jsonify(errno=RET.OK,errmsg='OK')
    
    """

    if request.method == 'PUT':

        action = request.json.get('action')
        order_id = request.json.get('order_id')
        if not all([action,order_id]):
            return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')
        if action not in ['accept','reject']:
            return jsonify(errno=RET.PARAMERR,errmsg='参数类型错误')

        try:
            order_id = int(order_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR,errmsg='参数类型错误')

        try:
            order = Order.query.filter_by(id=order_id).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='数据库查询失败')

        if action == 'accept':
            order.status = 'WAIT_COMMENT'

            try:
                db.session.add(order)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                db.session.rollback()
                return jsonify(errno=RET.DBERR,errmsg='数据库添加数据失败')

            return jsonify(errno=RET.OK,errmsg='OK')

        # action不是accept, 则是reject
        reason = request.json.get('reason')

        if not reason:
            return jsonify(errno=RET.PARAMERR,errmsg='需要填写原因')

        order.status = 'REJECTED'
        order.comment = reason

        try:
            db.session.add(order)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='数据库添加数据错误')

        return jsonify(errno=RET.OK,errmsg='OK')


    pass


@order_blue.route('/comment',methods=['PUT'])
@login_required
def comment():
    # 张鋆
    """
        评论订单
    步骤:
        1.判断用户是否登录 login_required
        2.获取参数 comment, order_id
        3.判断参数完整性
        4.根据order_id查找order对象
        5.添加数据到comment字段
        6.提交数据
        7.返回OK

    """

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg='用户未登录')

    comment = request.json.get('comment')
    order_id = request.json.get('order_id')

    if not all([comment,order_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')

    try:
        order = Order.query.filter_by(id=order_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库查询失败')

    order.comment = comment
    order.status = 'COMPLETE'

    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='数据库添加数据失败')

    return jsonify(errno=RET.OK,errmsg='OK')



    pass
